<?php
/**
 * Created by PhpStorm.
 * User: wenqiang.yq@gmail.com
 * Date: 16-3-6
 * Time: 下午6:33
 */

namespace ElasticSearch;


class EsIndex extends EsBase
{
    /**
     * 创建索引
     * @param $index
     * @param int $shardsNum
     * @param int $replicasNum
     * @param array $mapping
     * @param array $setting
     * @return mixed|string
     */
    public function create($index, $shardsNum = 1, $replicasNum = 1, $mapping = array(), $setting = array())
    {
        $uri = EsTools::specialUri($this->hosts, $index);
        $data["settings"] = array_merge(array(
            "number_of_shards" => $shardsNum,
            "number_of_replicas" => $replicasNum
        ), $setting);
        if ($mapping) {
            $data["mappings"] = $mapping;
        }
        return EsHttp::put($uri, $data);
    }

    /**
     * 删除索引
     * @param $index
     * @return mixed|string
     */
    public function delete($index)
    {
        if (is_array($index)) {
            $index = implode(",", $index);
        }
        $uri = EsTools::specialUri($this->hosts, $index);
        return EsHttp::delete($uri);
    }

    /**
     * 修改索引配置
     * @param $index
     * @param $setting
     * @param $mapping
     * @return mixed|string
     */
    public function update($index, $setting = array(), $mapping = array())
    {
        $uri = EsTools::specialUri($this->hosts, $index . "/_settings");
        $data = array();
        if ($setting) {
            $data["settings"] = $setting;
        }
        if ($mapping) {
            $data["mappings"] = $mapping;
        }
        return EsHttp::put($uri, $data);
    }

    /**
     * 配置索引的分析器
     * @param string $index 索引名称
     * @param string $analyzerName 分析器名称
     * @param string $type 分析器类型
     * @param string $stopwords 停用词表名称
     * @return mixed|string
     */
    public function setAnalyzer($index, $analyzerName, $type = "", $stopwords = "")
    {
        $settings = array(
            "analysis" => array(
                $analyzerName => array(
                    "type" => $type,
                    "stopwords" => $stopwords
                )
            )
        );
        return $this->update($index, $settings);

    }

    /**
     * 建立指向某个索引的别名
     * @param string $sourceName 索引名称
     * @param string $alias
     * @return mixed|string
     */
    public function alias($sourceName, $alias)
    {
        $uri = EsTools::specialUri($this->hosts, $sourceName . "/_alias/" . $alias);
        return EsHttp::put($uri);
    }

    /**
     * 获取索引的别名信息，或者别名的索引信息
     * @param string $sourceName
     * @param string $newName
     * @return mixed|string
     */
    public function aliasInfo($sourceName = "*", $newName = "*")
    {
        if (!$sourceName) {
            $sourceName = "*";
        }
        if (!$newName) {
            $newName = "*";
        }
        $uri = EsTools::specialUri($this->hosts, $sourceName . "/_alias/" . $newName);
        $result = EsHttp::get($uri);
        $data = array();
        foreach ($result as $index => $res) {
            $data[$index] = array_keys($res['aliases']);
        }
        return $data;
    }

    /**
     * 将一个索引别名从指向$oldIndex索引,替换成指向$newIndex索引
     * @param string $alias 别名
     * @param string $oldIndex 旧的索引实体
     * @param string $newIndex 新的索引实体
     * @return mixed|string
     */
    public function aliasTransfer($alias, $oldIndex, $newIndex)
    {
        $datas = array(
            "actions" => array(
                array(
                    "remove" => array( //移除旧的别名指向
                        "index" => $oldIndex,
                        "alias" => $alias
                    ),
                    "add" => array(  //添加新的别名指向
                        "index" => $newIndex,
                        "alias" => $alias
                    )
                )
            )
        );
        $uri = EsTools::specialUri($this->hosts, "_aliases");
        $jsonStr = json_encode($datas);
        return EsHttp::post($uri, $jsonStr);
    }

    /**
     * 添加模板
     * @param $templateName
     * @param $templateFile
     * @return array|mixed|string
     */
    public function addTemplate($templateName, $templateFile)
    {
        if (is_file($templateFile) && file_exists($templateFile)) {
            $file = $templateFile;
        } else {
            $file = ES_JSON_FOLD . "template" . DIRECTORY_SEPARATOR . "tpl_" . $templateName . ".json";
        }
        if (!file_exists($file)) {
            return array();
        }
        $queryBody = file_get_contents($file);
        $uri = EsTools::specialUri($this->hosts, "_template/{$templateName}");
        return EsHttp::put($uri, $queryBody);
    }

    /**
     * 修改模板
     * @param $templateName
     * @return mixed|string
     */
    public function delTemplate($templateName)
    {
        $uri = EsTools::specialUri($this->hosts, "_template/{$templateName}");
        return EsHttp::delete($uri);
    }

    /**
     * 获取模板
     * @param $templates
     * @return mixed|string
     */
    public function getTemplates($templates)
    {
        if (is_array($templates)) {
            $templates = implode(",", $templates);
        }
        $uri = EsTools::specialUri($this->hosts, "_template/{$templates}");
        return EsHttp::get($uri);
    }

    /**
     * 检测模板是否存在
     * @param $template
     * @return mixed|string
     */
    public function existsTemplate($template)
    {
        $uri = EsTools::specialUri($this->hosts, "_template/{$template}");
        return EsHttp::head($uri);
    }

    /**
     * 获取Es对索引中的类型的模式定义,即查看type中每个字段的类型
     * @param string $index
     * @param string $type
     * @return mixed|string
     */
    public function mapping($index = "", $type = "")
    {
        !$index && $index = $this->index;
        !$type && $type = $this->type;
        $uri = EsTools::specialUri($this->hosts, $index . "/_mapping/" . $type);
        $result = EsHttp::get($uri);
        $result[$index . "|" . $type] = $result[$index]["mappings"][$type]['properties'];
        unset($result[$index]);
        return $result;
    }
}